package com.example.demo.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectResult;
import com.example.demo.pojo.properties.AliyunOssProperties;

import java.io.InputStream;

public class AliyunOssUtil {

    private static OSS createOssClient(AliyunOssProperties aliyunOssProperties) {
        // 使用DefaultCredentialProvider方法直接设置AK和SK
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(aliyunOssProperties.getAccessKeyId(), aliyunOssProperties.getAccessKeySecret());

        // 创建OSSClient实例。
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(aliyunOssProperties.getEndpoint())
                .credentialsProvider(credentialsProvider)
                .region(aliyunOssProperties.getRegion())
                .build();

        return ossClient;
    }

    /**
     * 上传文件
     * @param aliyunOssProperties 阿里云对象存储服务的各种配置信息类
     * @param inputStream 上传的文件的输入流
     * @param objectName 唯一文件存储名
     * @return 文件存储的url
     */
    public static String uploadFile(AliyunOssProperties aliyunOssProperties, InputStream inputStream, String objectName) {
        OSS ossClient = createOssClient(aliyunOssProperties);

        String bucketName = aliyunOssProperties.getBucketName();

        PutObjectResult putObjectResult = ossClient.putObject(bucketName, objectName, inputStream);

        String endpoint = aliyunOssProperties.getEndpoint();

        String url = "https://" + bucketName + "." + endpoint.substring(endpoint.lastIndexOf("/") + 1) + "/" + objectName;

        if (ossClient != null) {
            ossClient.shutdown();
        }

        return url;
    }

    /**
     * 删除文件
     * @param aliyunOssProperties 阿里云对象存储服务的各种配置信息类
     * @param objectName 唯一文件存储名
     * @return 操作是否成功
     */
    public static boolean deleteFile(AliyunOssProperties aliyunOssProperties, String objectName) {
        OSS ossClient = createOssClient(aliyunOssProperties);

        String bucketName = aliyunOssProperties.getBucketName();

            // 判断文件是否存在。如果返回值为true，则文件存在，否则存储空间或者文件不存在。
            boolean found = ossClient.doesObjectExist(bucketName, objectName);

            if (!found) {
                System.out.println("文件不存在");
                return false;
            }

            ossClient.deleteObject(bucketName, objectName);

            if (ossClient != null) {
                ossClient.shutdown();
            }

            return true;
    }
}
